package com.ubs.training.server.dao.impl.hbm;

import com.ubs.training.server.dao.ContractDao;
import com.ubs.training.server.dao.model.Contract;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;

import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/27/12
 * Time: 3:50 AM
 * To change this template use File | Settings | File Templates.
 */
@Repository("hbmContractDao")
public class HbmContractDao implements ContractDao {
    private SessionFactory factory;

    private HibernateTemplate tpl;

    public SessionFactory getFactory() {
        return factory;
    }

    @Autowired
    public void setFactory(SessionFactory factory) {
        tpl = new HibernateTemplate(factory);
        this.factory = factory;
    }

    @Override
    public List<Contract> getAll() {
        return tpl.loadAll(Contract.class);
    }

    @Override
    public List<Contract> getByClientId(int clientId) {
        DetachedCriteria dc = DetachedCriteria.forClass(Contract.class)
                .add(Property.forName("idClient").eq(clientId));


           /*     (createCriteria(Contract.class)
                .add(Property.forName("idClient").eq(clientId))
                .list(););*/
        List resList = tpl.findByCriteria(dc);
        return resList;
    }


    @Override
    public Contract getById(int id) {
        return tpl.load(Contract.class, id);
    }

    @Override
    public void add(Contract contract) {
        tpl.save(contract);
    }

    @Override
    public void update(Contract contract) {
        tpl.merge(contract);
        tpl.update(contract);
    }

    @Override
    public void delete(Contract contract) {
        tpl.merge(contract);
        tpl.delete(contract);

    }

    @Override
    public void delete(int contractId) {
        Contract con = getById(contractId);
        tpl.merge(con);
        tpl.delete(con);
    }

}
